<template>
	<section>

		<el-col :span="24" class="toolbar"  style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-button type="primary" @click="handleAdd">添加视频</el-button>
				</el-form-item>				
				<el-form-item>
					<el-input v-model="key"  placeholder="输入查询的关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getList">查询</el-button>
				</el-form-item>
			</el-form>
		</el-col>			
		<!--列表-->

		<el-tabs v-model="isShared"  type="card">
		    <el-tab-pane label="我的视频" name=' '></el-tab-pane>
		    <el-tab-pane label="共享视频" name='1'></el-tab-pane>
		    <el-tab-pane label="内置视频" name='2'></el-tab-pane>
		</el-tabs>			
		<!--工具条-->		
		<el-table :data="Lists" highlight-current-row v-loading="loading" style="width: 100%;" @sort-change="sortChange">
			<el-table-column  type="index" width='80'>
			</el-table-column>
			<el-table-column prop="name" label="视频名称" width="200">
			</el-table-column>
			<el-table-column prop="realName" label="创建人" width="200" >
			</el-table-column>
			<el-table-column prop="orgName" label="所属单位"width="200" >
			</el-table-column>			
			<el-table-column prop="createTime" label="上传时间" width="200" >
			</el-table-column>
			<el-table-column prop="referenceCount" label="引用次数" width="200">
			</el-table-column>			
			<el-table-column prop="birth" min-width="200" label="操作" fixed="right" >
				<template scope="scope">
					<el-button size="small" v-if="isShared==' '||$store.state.role=='admin'" type="danger" @click="handleDel(scope.row)">删除</el-button>
					<el-button size="small" v-if="isShared==' '||$store.state.role=='admin'" type="primary" @click="getone(scope.row)">编辑</el-button>
					<el-button size="small" type="success" @click="lookone(scope.row)">查看</el-button>
					<el-button size="small" type="warning" v-if="scope.row.isShared==false&&isShared!=2&&$store.state.role!='admin'" @click="goShared(scope.row,1)">共享</el-button>
					<el-button size="small" type="info" v-if="scope.row.isShared==true&&isShared!=2">已共享</el-button>
				</template>					
			</el-table-column>
		</el-table>
		<!--工具-->
		<el-col :span="24" class="toolbar">
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>		
		<!--新增界面-->
		<el-dialog  title="添加视频" :fullscreen="false" custom-class="videodialog" width="30%"  v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addvideo"  :rules="addvideorule" ref="addvideo">		
				<el-form-item label="添加视频" prop="name">
					<el-row :gutter="5">
						<el-col :span="12">
							<el-input v-model="addvideo.name" placeholder="视频名称（15字以内）"  auto-complete="off"></el-input>
						</el-col>
						<el-col :span="6">
							<el-upload
							  class="upload-demo"
							  action="videoupload"
							  :before-upload="beforeupload"
							  :file-list="fileList"
							  limit='1'
							  accept="video/*">
							  <el-button  type="primary">选择文件</el-button>
							</el-upload>						
						</el-col>	
					</el-row>
				</el-form-item>		
				<el-form-item label="视频类型"  prop="type" >
				    <el-radio-group v-model="addvideo.type">
				      <el-radio label="0">创业基础视频</el-radio>
				      <el-radio label="1">案例分析视频</el-radio>
				    </el-radio-group>
				</el-form-item>	
				<el-form-item label="所属商业模式版块儿" v-if="addvideo.type==0" label-width="150px"  prop="bussinsmodel" >
				    <el-select placeholder="请选择版块儿" v-model="addvideo.bussinsmodel">
				      <el-option v-for="el in bussinessList" :value="el.businessModelId" :label="el.name"></el-option>
				    </el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--编辑界面-->
		<el-dialog  title="编辑视频" :fullscreen="false" custom-class="videodialog" width="30%"  v-model="editFormVisible" :close-on-click-modal="false">
		
			<el-form :model="editvideo"  :rules="editvideorule" ref="editvideo">		
				<el-form-item label="修改视频" prop="name">
					<el-row :gutter="5">
						<el-col :span="12">
							<el-input v-model="editvideo.name" placeholder="视频名称（15字以内）"  auto-complete="off"></el-input>
						</el-col>
						<el-col :span="6">
							<el-upload
							  class="upload-demo"
							  action="videoupload"
							  :on-preview="fileclick"
							  :before-upload="editbeforeupload"
							  :file-list="editfileList"
							  limit='1'
							  accept="video/*">
							  <el-button  type="primary">选择文件</el-button>
							</el-upload>						
						</el-col>	
					</el-row>
				</el-form-item>		
				<template>
					<video width="100%" class="videoauto" v-bind:src="editvideo.path" height="" controls>
					</video>
				</template>
				<el-form-item label="视频类型"  prop="courseStage" >
				    <el-radio-group v-model="editvideo.courseStage">
				      <el-radio label="0">创业基础视频</el-radio>
				      <el-radio label="1">案例分析视频</el-radio>
				    </el-radio-group>
				</el-form-item>	
				<el-form-item label="所属商业模式版块儿" v-if="editvideo.courseStage==0" label-width="150px"  prop="businessModelId" >
				    <el-select placeholder="请选择版块儿" v-model="editvideo.businessModelId">
				      <el-option v-for="el in bussinessList" :value="el.businessModelId" :label="el.name"></el-option>
				    </el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>	
		<!--查看视频界面-->
		<el-dialog  title="查看视频" :fullscreen="false" custom-class="videodialog" width="30%"  v-model="lookVisible" :close-on-click-modal="false">	
			<template>
				<video width="100%"  v-bind:src="lookvideo.path" height="" controls>
				</video>
			</template>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="lookVisible = false">关闭</el-button>
			</div>
		</el-dialog>			
	</section>
</template>
<script>
	import { videolist,videodelete,videoadd,videoone,videoedit,bussinesslist,videonamerule,videolistbuil} from '../../api/api';

	//import NProgress from 'nprogress'
	export default {
		data() {
			var rulesname=(rules,value,callback)=>{
				let params={name:this.addvideo.name};
				videonamerule(params).then((r)=>{
					if(!r){
						callback(new Error('视频名称重复'))
					}else{
						callback()
					}
				})
			}	
			var editrulesname=(rules,value,callback)=>{
				if(this.editvideo.checkname!=this.editvideo.name){			
					let params={name:this.editvideo.name};
					videonamerule(params).then((r)=>{
						if(!r){
							callback(new Error('视频名称重复'))
						}else{
							callback()
						}
					})
				}else{
					callback()
				}
			}	
			let namelengthrule=(rule, value, callback)=>{
			  if (value.length > 15) {
			    callback(new Error('限制字数15字以内'))
			  } else {
			    callback()
			  }							
			}				
			return {
				Type:"",
				addFormVisible: false,
				addLoading: false,	
				autoVideo:false,
				editFormVisible: false,
				editLoading: false,						
				loading: false,
				lookVisible:false,
				videoupload:"video",
				Lists:[],
				fileList:[],
				editfileList:[],	
				bussinessList:[],
				lookvideo:{
					path:""
				},
				addvideo:{
					name:"",
					type:"",
					bussinsmodel:"",
					src:""
				},
				editvideo:{
					name:"",
					type:"",
					bussinsmodel:"",
					src:""					
				},
				param:"",
				eidtparam:"",
				addvideorule: {
					name: [
						{ required: true, message: '请填写视频名称', trigger: 'blur' },
						{validator:rulesname,trigger: 'blur'}	,
						{validator:namelengthrule,trigger: 'blur'}
					],
					type:[
						{ required: true, message: '请选择视频类别', trigger: 'blur' }
					],
					bussinsmodel:[
						{ required: true, message: '请选择所属商业模式版块儿', trigger: 'blur' }
					],
				},		
				editvideorule: {
					name: [
						{ required: true, message: '请填写视频名称', trigger: 'blur' },
						{validator:editrulesname,trigger: 'blur'},
						{validator:namelengthrule,trigger: 'blur'}
					],
					courseStage:[
						{ required: true, message: '请选择视频类别', trigger: 'blur' }
					],
					businessModelId:[
						{ required: true, message: '请选择所属商业模式版块儿', trigger: 'blur' }
					],
				},						
				form:{
					resource:""
				},
				page:"1",
				pagesize:"10",
				total:'',
				key:"",
				isShared:" ",
				isSelf:'1',
			}
		},
		watch:{
			'isShared':function(){
				this.pageNum='1';
				if(this.isShared==1){
					this.isSelf='0'
				}else{
					this.isSelf='1'
				}
				this.getList();
			}
		},
		methods: {	
		    sortChange:function(column, prop, order){
				if(column){
			      var type='';
			      if(column.prop=='createTime'){
			      	column.prop='create_time';
			      }else if(column.prop=='referenceCount'){
			      	column.prop='reference_count';
			      }
			      if(column.order=="ascending"){
			      	type=column.prop;	
			      }else if(column.order=='descending'){
			      	type=column.prop+' '+'desc';
			      }
			      this.getList(type)			 	
				}
		    },		
			goShared:function(row,type){
				this.$confirm('确定共享资源吗?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',					
					type: 'warning'
				}).then(() => {
					var params=new FormData();
					params.append('isShared',type);
					params.append('videoId',row.videoId);
					videoedit(params).then((r) => {
						if(!r.error){
							this.$message({
								message: '共享成功',
								type: 'success'
							});
							this.getList();									
						}else{
							this.$message({
								message: '共享失败',
								type: 'error'
							});						
						}
					})	
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '取消共享'		
					});						
				});				
			
			},
			handleAdd: function () {
				this.addFormVisible = true;
			},
			fileclick:function(){
				$('.videoauto').toggle()
			},
			isSharedclick:function(type){
				this.isShared=type;
				this.getList();
			},
			//获取商业模式列表
			getbussinesslist:function(){
				bussinesslist().then((res)=>{
					$.each(res, function(i,value) {
						value.businessModelId=JSON.stringify(value.businessModelId)
					});
					this.bussinessList=res;
				})
			},	
			//获取项目列表
			getList: function (type) {
				this.loading = true;
				//NProgress.start();
				if(this.isShared!=2){
					let params={pageNum:this.page,pageSize:this.pagesize,key:this.key,isShared:this.isShared,isSelf:this.isSelf,orderByClause:type};
					videolist(params).then((res) => {
						this.total=res.total;					
						this.Lists = res.list;
						this.loading = false;
						//NProgress.done();
					});					
				}else{
					let params={pageNum:this.page,pageSize:this.pagesize,key:this.key,orderByClause:type};
					videolistbuil(params).then((res) => {
						this.total=res.total;					
						this.Lists = res.list;
						this.loading = false;
						//NProgress.done();
					});					
				}
			},		
			lookone:function(row){
				this.lookVisible=true;
				this.lookvideo.path=row.path;
			},
			getone:function(row){
				var params=row.videoId;
				videoone(params).then((res)=>{			
					this.editFormVisible=true;
					res.checkname=res.name;
					res.courseStage=JSON.stringify(res.courseStage);
					res.businessModelId=JSON.stringify(res.businessModelId);
					res.src='';
					this.editvideo = Object.assign({}, res);
					var info={name:res.name,url:res.url};
					this.editfileList=[];
					this.editfileList.push(info);
				})
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getList();
			},	
            beforeupload(file) {
                //创建临时的路径来展示图片
                var windowURL = window.URL || window.webkitURL;
                var videoname= file.name;     
                this.addvideo.name=file.name;
                this.addvideo.src=windowURL.createObjectURL(file);
                let onevideo={name:videoname,url:this.addvideo.src};
                this.fileList=[];
                this.fileList.push(onevideo);
                //重新写一个表单上传的方法
                this.param = new FormData();
                this.param.append('file', file, file.name);
                return false;
            },	
            editbeforeupload(file) {
                console.log(file);
                //创建临时的路径来展示图片
                var windowURL = window.URL || window.webkitURL;
                var videoname= file.name;     
                this.editvideo.name=file.name;
                this.editvideo.src=windowURL.createObjectURL(file);
                let onevideo={name:videoname,url:this.addvideo.src};
                this.editfileList=[];
                this.editfileList.push(onevideo);
                //重新写一个表单上传的方法
                this.eidtparam = new FormData();
                this.eidtparam.append('file', file, file.name);
                return false;
            },	            
			handleDel:function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',					
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para =row.videoId;
					
					videodelete(para).then((res) => {
						if(!res.error){
							this.listLoading = false;
							//NProgress.done();
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.getList();							
						}else{
							this.$message({
								type: 'error',
								message: '取消失败'		
							});								
						}
					});
				}).catch(() => {
					this.$message({
						type: 'error',
						message: '取消失败'			
					});						
				});
			},
			//新增
			addSubmit: function () {
				if(this.addvideo.src==''){
			        this.$message({
			          showClose: true,
			          message: '请选择上传文件',
			          type: 'error'
			        });					
			        return;
				}
				this.$refs.addvideo.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							this.param.append('name',this.addvideo.name);
							this.param.append('courseStage',this.addvideo.type);
							if(this.addvideo.type==0){
								this.param.append('businessModelId',this.addvideo.bussinsmodel);				
							}
							videoadd(this.param).then((r) => {
								if(!r.error){
									this.addLoading = false;
									this.$message({
										message: '成功上传',
										type: 'success'
									});
									this.fileList=[];
									this.$refs['addvideo'].resetFields();
									this.addFormVisible = false;
									this.param='';
									this.getList();									
								}else{
									this.addLoading = false;
									this.param='';
									this.$message({
										message: '上传失败',
										type: 'error'
									});										
								}
							}).catch(()=>{
								this.addLoading = false;
								this.param='';
								this.$message({
									message: '上传失败',
									type: 'error'
								});								
							});
						});
					}
				});
			},
			//编辑
			editSubmit: function () {
				if(this.editvideo.src==''){
	                this.eidtparam = new FormData();        				
				}
				this.$refs.editvideo.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							this.eidtparam.append('path',this.editvideo.path);	
							this.eidtparam.append('name',this.editvideo.name);
							this.eidtparam.append('videoId',this.editvideo.videoId);
							this.eidtparam.append('courseStage',this.editvideo.courseStage);
							if(this.editvideo.courseStage==0){
								this.eidtparam.append('businessModelId',this.editvideo.businessModelId);
							}							
							videoedit(this.eidtparam).then((r) => {
								if(!r.error){
									this.editLoading = false;
									this.$message({
										message: '更新成功',
										type: 'success'
									});
									this.$refs['editvideo'].resetFields();
									this.editFormVisible = false;
									this.eidtparam='',
									this.getList();									
								}else{
									this.editLoading = false;
									this.eidtparam='',
									this.$message({
										message: '更新失败',
										type: 'error'
									});										
								}
							}).catch(()=>{
								this.editLoading = false;
								this.eidtparam='',
								this.$message({
									message: '更新失败',
									type: 'error'
								});								
							});
						});
					}
				});
			},			
		},
		mounted() {
			this.getList();
			this.getbussinesslist()
		}
	};

</script>

<style>
.videodialog {
	width: 30%;
}
.videoauto{
	display: none;
}
</style>